﻿using System;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace WebCoreAdmin.Middlewares
{
    public class ClientAccountUserPasswordMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public ClientAccountUserPasswordMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<ClientAccountUserPasswordMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {
             if (context.Connection.ClientCertificate!=null)
            {
                try
                {
                    if (context.User.Identity.Name == null)
                    {
                        if ("error".Length==0)
                        {
                            _logger.LogError("Certificate is not valid");
                            context.Response.StatusCode = 403;
                            return;
                        }

                        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                        identity.AddClaim(new Claim(ClaimTypes.Name, "a"));
//                        identity.AddClaim(new Claim(ClaimTypes.Name, userName));
//                        identity.AddClaim(new Claim(ClaimTypes.Role, userName));
                        

                        await context.SignInAsync(scheme: CookieAuthenticationDefaults.AuthenticationScheme, principal: new ClaimsPrincipal(identity));
                        await _next.Invoke(context);
                    }
                   
                   
                }
                catch (Exception ex)
                {
                    //What to do with exceptions in middleware?
                    _logger.LogError(ex.Message, ex);
                    await context.Response.WriteAsync(ex.Message);
                    context.Response.StatusCode = 403;
                }
            }
            else
            {
                _logger.LogError("X - ARR - ClientCert header is missing");
                context.Response.StatusCode = 403;
            }
        }



    }


    public static class ClientAccountUserPasswordMiddlewareExtensions
    {
        public static IApplicationBuilder ClientAccountUserPasswordMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ClientAccountUserPasswordMiddleware>();
        }
    }
}
